// 目录导航交互
document.addEventListener('DOMContentLoaded', function() {
    const search = document.getElementById('searchBox');
    const tocLinks = document.querySelectorAll('#tocList a');
    const printBtn = document.getElementById('printBtn');
    const topBtn = document.getElementById('topBtn');
    
    // 平滑滚动并高亮目录
    tocLinks.forEach(a => {
        a.addEventListener('click', e => {
            e.preventDefault();
            document.querySelectorAll('#tocList a').forEach(x => x.classList.remove('active'));
            a.classList.add('active');
            const id = a.getAttribute('href').slice(1);
            const el = document.getElementById(id);
            if (el) {
                window.scrollTo({
                    top: el.offsetTop - 80,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // 搜索功能
    search.addEventListener('input', () => {
        const query = search.value.trim().toLowerCase();
        tocLinks.forEach(link => {
            const text = link.textContent.toLowerCase();
            if (text.includes(query)) {
                link.parentElement.style.display = '';
            } else {
                link.parentElement.style.display = 'none';
            }
        });
    });
    
    // 打印功能
    printBtn.addEventListener('click', () => {
        window.print();
    });
    
    // 回到顶部
    topBtn.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
    
    // 滚动时高亮当前查看的章节
    window.addEventListener('scroll', () => {
        const sections = document.querySelectorAll('section');
        let currentSection = '';
        
        sections.forEach(section => {
            const sectionTop = section.offsetTop - 100;
            if (window.scrollY >= sectionTop) {
                currentSection = section.id;
            }
        });
        
        tocLinks.forEach(link => {
            link.classList.remove('active');
            if (link.getAttribute('href') === `#${currentSection}`) {
                link.classList.add('active');
            }
        });
    });
    
    // 初始高亮第一个目录项
    tocLinks[0].classList.add('active');
});